package com.pai4j.zwiki.service.diagram;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pai4j.zwiki.domain.entity.CodeStructureEntity;
import com.pai4j.zwiki.repository.CodeStructureRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 增强的图表生成服务
 * 生成多种类型的项目分析图表
 *
 * @author pai4j
 * @since 2025-10-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DiagramEnhancedService {

    private final CodeStructureRepository codeStructureRepository;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${zwiki.workspace.base-path:/tmp/zwiki-workspace}")
    private String workspaceBasePath;

    /**
     * 生成完整的图表集合（适用于毕业论文）
     *
     * @param taskId 任务ID
     * @return 所有生成的图表文件路径
     */
    public Map<String, String> generateAllDiagrams(String taskId) {
        log.info("开始生成完整图表集合（毕业论文专用）, 任务ID: {}", taskId);

        Map<String, String> diagrams = new HashMap<>();

        try {
            // 1. 类图 - 代码结构图
            String classDiagram = generateDetailedClassDiagram(taskId);
            diagrams.put("classDiagram", classDiagram);

            // 2. 包依赖图
            String packageDependency = generatePackageDependencyDiagram(taskId);
            diagrams.put("packageDependency", packageDependency);

            // 3. 时序图 - 调用链图
            String sequenceDiagram = generateCallChainDiagram(taskId);
            diagrams.put("sequenceDiagram", sequenceDiagram);

            // 4. 多层架构图
            String layerArchitecture = generateLayerArchitectureDiagram(taskId);
            diagrams.put("layerArchitecture", layerArchitecture);

            // 5. 组件交互图
            String componentInteraction = generateComponentInteractionDiagram(taskId);
            diagrams.put("componentInteraction", componentInteraction);

            // 6. 模块关系图
            String moduleRelation = generateModuleRelationDiagram(taskId);
            diagrams.put("moduleRelation", moduleRelation);

            // 7. 业务流程图
            String businessFlow = generateBusinessFlowDiagram(taskId);
            diagrams.put("businessFlow", businessFlow);

            // 8. 状态机图
            String stateMachine = generateStateMachineDiagram(taskId);
            diagrams.put("stateMachine", stateMachine);

            // 9. 设计模式图
            String designPatterns = generateDesignPatternDiagram(taskId);
            diagrams.put("designPatterns", designPatterns);

            // 10. 部署架构图
            String deploymentArchitecture = generateDeploymentDiagram(taskId);
            diagrams.put("deploymentArchitecture", deploymentArchitecture);

            // 11. 监控架构图
            String monitoringArchitecture = generateMonitoringDiagram(taskId);
            diagrams.put("monitoringArchitecture", monitoringArchitecture);

            // 12. 依赖强度热力图数据（用于前端渲染）
            String dependencyHeatmap = generateDependencyHeatmapData(taskId);
            diagrams.put("dependencyHeatmap", dependencyHeatmap);

            log.info("图表集合生成完成，共生成 {} 个图表", diagrams.size());

        } catch (Exception e) {
            log.error("生成图表集合失败", e);
        }

        return diagrams;
    }

    /**
     * 生成详细的类图
     */
    public String generateDetailedClassDiagram(String taskId) {
        log.info("生成详细类图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 只取核心类（前20个）
            List<CodeStructureEntity> coreClasses = structures.stream()
                    .filter(s -> "class".equals(s.getStructureType()) || "interface".equals(s.getStructureType()))
                    .limit(20)
                    .collect(Collectors.toList());

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 详细类图\n");
            uml.append("skinparam classAttributeIconSize 0\n");
            uml.append("skinparam linetype ortho\n\n");

            // 按包分组
            Map<String, List<CodeStructureEntity>> packageGroups = coreClasses.stream()
                    .collect(Collectors.groupingBy(
                            s -> s.getPackageName() != null ? s.getPackageName() : "default"
                    ));

            for (Map.Entry<String, List<CodeStructureEntity>> entry : packageGroups.entrySet()) {
                String packageName = entry.getKey();
                
                if (!"default".equals(packageName)) {
                    uml.append("package \"").append(getSimplePackageName(packageName)).append("\" {\n");
                }

                for (CodeStructureEntity clazz : entry.getValue()) {
                    generateClassDefinition(uml, clazz);
                }

                if (!"default".equals(packageName)) {
                    uml.append("}\n\n");
                }
            }

            // 添加关系
            addRelationships(uml, coreClasses);

            uml.append("@enduml");

            return generateDiagram(taskId, "detailed-class-diagram", uml.toString());

        } catch (Exception e) {
            log.error("生成详细类图失败", e);
            return null;
        }
    }

    /**
     * 生成包依赖图
     */
    public String generatePackageDependencyDiagram(String taskId) {
        log.info("生成包依赖图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 统计包之间的依赖关系
            Map<String, Set<String>> packageDeps = new HashMap<>();

            for (CodeStructureEntity structure : structures) {
                String pkg = structure.getPackageName();
                if (pkg == null) continue;

                if (structure.getDependencies() != null) {
                    try {
                        @SuppressWarnings("unchecked")
                        List<String> deps = objectMapper.readValue(structure.getDependencies(), List.class);
                        
                        for (String dep : deps) {
                            // 找到依赖类所属的包
                            String depPkg = findPackageForClass(dep, structures);
                            if (depPkg != null && !depPkg.equals(pkg)) {
                                packageDeps.computeIfAbsent(pkg, k -> new HashSet<>()).add(depPkg);
                            }
                        }
                    } catch (Exception e) {
                        // 忽略
                    }
                }
            }

            // 生成 PlantUML
            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 包依赖图\n");
            uml.append("skinparam packageStyle rectangle\n\n");

            // 添加所有包
            Set<String> allPackages = new HashSet<>(packageDeps.keySet());
            packageDeps.values().forEach(allPackages::addAll);

            for (String pkg : allPackages) {
                uml.append("package \"").append(getSimplePackageName(pkg)).append("\" as ")
                   .append(packageToId(pkg)).append("\n");
            }

            uml.append("\n");

            // 添加依赖关系
            for (Map.Entry<String, Set<String>> entry : packageDeps.entrySet()) {
                String from = packageToId(entry.getKey());
                for (String toPkg : entry.getValue()) {
                    String to = packageToId(toPkg);
                    uml.append(from).append(" --> ").append(to).append("\n");
                }
            }

            uml.append("\n@enduml");

            return generateDiagram(taskId, "package-dependency", uml.toString());

        } catch (Exception e) {
            log.error("生成包依赖图失败", e);
            return null;
        }
    }

    /**
     * 生成调用链图
     */
    public String generateCallChainDiagram(String taskId) {
        log.info("生成调用链图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 找到所有 Controller 作为入口
            List<CodeStructureEntity> controllers = structures.stream()
                    .filter(s -> s.getName().endsWith("Controller"))
                    .limit(5)
                    .collect(Collectors.toList());

            if (controllers.isEmpty()) {
                log.warn("未找到 Controller 类");
                return null;
            }

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 调用链图\n");
            uml.append("skinparam sequenceArrowThickness 2\n");
            uml.append("skinparam roundcorner 20\n\n");

            // 为每个 Controller 生成调用序列
            for (CodeStructureEntity controller : controllers) {
                uml.append("actor User\n");
                uml.append("participant \"").append(controller.getName()).append("\" as C\n");
                
                // 追踪依赖
                if (controller.getDependencies() != null) {
                    try {
                        @SuppressWarnings("unchecked")
                        List<String> deps = objectMapper.readValue(controller.getDependencies(), List.class);
                        
                        for (int i = 0; i < Math.min(3, deps.size()); i++) {
                            uml.append("participant \"").append(deps.get(i)).append("\" as D").append(i).append("\n");
                        }
                        
                        uml.append("\nUser -> C: 请求\n");
                        for (int i = 0; i < Math.min(3, deps.size()); i++) {
                            uml.append("C -> D").append(i).append(": 调用\n");
                            uml.append("D").append(i).append(" --> C: 返回\n");
                        }
                        uml.append("C --> User: 响应\n\n");
                        
                    } catch (Exception e) {
                        // 忽略
                    }
                }
            }

            uml.append("@enduml");

            return generateDiagram(taskId, "call-chain", uml.toString());

        } catch (Exception e) {
            log.error("生成调用链图失败", e);
            return null;
        }
    }

    /**
     * 生成架构分层图
     */
    public String generateLayerArchitectureDiagram(String taskId) {
        log.info("生成架构分层图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 按层分类
            Map<String, List<String>> layers = new HashMap<>();
            layers.put("Controller", new ArrayList<>());
            layers.put("Service", new ArrayList<>());
            layers.put("Repository", new ArrayList<>());
            layers.put("Entity", new ArrayList<>());

            for (CodeStructureEntity structure : structures) {
                String name = structure.getName();
                String pkg = structure.getPackageName();
                
                if (name.endsWith("Controller")) {
                    layers.get("Controller").add(name);
                } else if (name.endsWith("Service") || (pkg != null && pkg.contains("service"))) {
                    layers.get("Service").add(name);
                } else if (name.endsWith("Repository") || name.endsWith("DAO") || 
                          (pkg != null && pkg.contains("repository"))) {
                    layers.get("Repository").add(name);
                } else if (name.endsWith("Entity") || (pkg != null && pkg.contains("entity"))) {
                    layers.get("Entity").add(name);
                }
            }

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 架构分层图\n");
            uml.append("skinparam packageStyle rectangle\n\n");

            // 生成各层
            for (String layer : Arrays.asList("Controller", "Service", "Repository", "Entity")) {
                List<String> classes = layers.get(layer);
                if (!classes.isEmpty()) {
                    uml.append("package \"").append(layer).append(" 层\" {\n");
                    classes.stream().limit(5).forEach(c -> 
                        uml.append("  class ").append(c).append("\n")
                    );
                    if (classes.size() > 5) {
                        uml.append("  note \"... 还有 ").append(classes.size() - 5)
                           .append(" 个类\" as N").append(layer).append("\n");
                    }
                    uml.append("}\n\n");
                }
            }

            // 添加层间依赖
            uml.append("Controller ..> Service\n");
            uml.append("Service ..> Repository\n");
            uml.append("Repository ..> Entity\n");

            uml.append("\n@enduml");

            return generateDiagram(taskId, "layer-architecture", uml.toString());

        } catch (Exception e) {
            log.error("生成架构分层图失败", e);
            return null;
        }
    }

    /**
     * 生成模块关系图
     */
    public String generateModuleRelationDiagram(String taskId) {
        log.info("生成模块关系图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 提取顶层包作为模块
            Set<String> modules = structures.stream()
                    .map(CodeStructureEntity::getPackageName)
                    .filter(Objects::nonNull)
                    .map(this::getTopLevelPackage)
                    .collect(Collectors.toSet());

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 模块关系图\n\n");

            for (String module : modules) {
                String simpleName = getSimplePackageName(module);
                uml.append("component [").append(simpleName).append("] as ").append(packageToId(module)).append("\n");
            }

            uml.append("\n@enduml");

            return generateDiagram(taskId, "module-relation", uml.toString());

        } catch (Exception e) {
            log.error("生成模块关系图失败", e);
            return null;
        }
    }

    /**
     * 生成依赖强度热力图数据
     */
    public String generateDependencyHeatmapData(String taskId) {
        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 统计类之间的依赖强度
            Map<String, Map<String, Integer>> heatmap = new HashMap<>();

            for (CodeStructureEntity structure : structures) {
                String className = structure.getName();
                
                if (structure.getDependencies() != null) {
                    try {
                        @SuppressWarnings("unchecked")
                        List<String> deps = objectMapper.readValue(structure.getDependencies(), List.class);
                        
                        Map<String, Integer> depCounts = new HashMap<>();
                        for (String dep : deps) {
                            depCounts.put(dep, depCounts.getOrDefault(dep, 0) + 1);
                        }
                        
                        heatmap.put(className, depCounts);
                    } catch (Exception e) {
                        // 忽略
                    }
                }
            }

            // 转为 JSON
            return objectMapper.writeValueAsString(heatmap);

        } catch (Exception e) {
            log.error("生成依赖热力图数据失败", e);
            return "{}";
        }
    }

    // ========== 辅助方法 ==========

    private void generateClassDefinition(StringBuilder uml, CodeStructureEntity clazz) {
        String type = "interface".equals(clazz.getStructureType()) ? "interface" : "class";
        
        uml.append("  ").append(type).append(" ").append(clazz.getName()).append(" {\n");
        
        // 添加注解信息
        if (clazz.getAnnotations() != null) {
            try {
                @SuppressWarnings("unchecked")
                List<String> annotations = objectMapper.readValue(clazz.getAnnotations(), List.class);
                for (String ann : annotations.stream().limit(3).collect(Collectors.toList())) {
                    uml.append("    <<").append(ann).append(">>\n");
                }
            } catch (Exception e) {
                // 忽略
            }
        }
        
        uml.append("  }\n");
    }

    private void addRelationships(StringBuilder uml, List<CodeStructureEntity> classes) {
        Map<String, CodeStructureEntity> classMap = classes.stream()
                .collect(Collectors.toMap(CodeStructureEntity::getName, c -> c, (a, b) -> a));

        for (CodeStructureEntity clazz : classes) {
            if (clazz.getDependencies() != null) {
                try {
                    @SuppressWarnings("unchecked")
                    List<String> deps = objectMapper.readValue(clazz.getDependencies(), List.class);
                    
                    for (String dep : deps) {
                        if (classMap.containsKey(dep)) {
                            uml.append(clazz.getName()).append(" ..> ").append(dep).append("\n");
                        }
                    }
                } catch (Exception e) {
                    // 忽略
                }
            }
        }
    }

    private String findPackageForClass(String className, List<CodeStructureEntity> structures) {
        return structures.stream()
                .filter(s -> className.equals(s.getName()))
                .map(CodeStructureEntity::getPackageName)
                .findFirst()
                .orElse(null);
    }

    private String getSimplePackageName(String packageName) {
        if (packageName == null) return "default";
        String[] parts = packageName.split("\\.");
        return parts[parts.length - 1];
    }

    private String getTopLevelPackage(String packageName) {
        if (packageName == null) return "default";
        String[] parts = packageName.split("\\.");
        return parts.length >= 3 ? String.join(".", parts[0], parts[1], parts[2]) : packageName;
    }

    private String packageToId(String packageName) {
        return packageName.replaceAll("[^a-zA-Z0-9]", "_");
    }

    private String getUmlModifier(String accessModifier) {
        return switch (accessModifier) {
            case "public" -> "+";
            case "private" -> "-";
            case "protected" -> "#";
            default -> "~";
        };
    }

    private String generateDiagram(String taskId, String diagramName, String plantUmlCode) {
        try {
            Path diagramDir = Paths.get(workspaceBasePath, taskId, "diagrams");
            Files.createDirectories(diagramDir);

            String pngFilename = diagramName + ".png";
            Path pngFilePath = diagramDir.resolve(pngFilename);

            SourceStringReader reader = new SourceStringReader(plantUmlCode);
            try (FileOutputStream fos = new FileOutputStream(pngFilePath.toFile())) {
                reader.outputImage(fos, new FileFormatOption(FileFormat.PNG));
            }

            log.info("图表生成成功: {}", pngFilePath);
            return pngFilePath.toString();

        } catch (IOException e) {
            log.error("生成PlantUML图表失败", e);
            return null;
        }
    }

    /**
     * 生成组件交互图
     * 展示各个组件之间的交互关系
     */
    public String generateComponentInteractionDiagram(String taskId) {
        log.info("生成组件交互图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 组件交互图\n");
            uml.append("skinparam componentStyle rectangle\n\n");

            uml.append("' 前端层\n");
            uml.append("package \"前端\" {\n");
            uml.append("  [Web前端] as frontend\n");
            uml.append("}\n\n");

            uml.append("' 网关层\n");
            uml.append("package \"网关层\" {\n");
            uml.append("  [API网关] as gateway\n");
            uml.append("}\n\n");

            uml.append("' 应用层\n");
            uml.append("package \"应用层\" {\n");
            
            // 找到所有Controller作为应用组件
            List<CodeStructureEntity> controllers = structures.stream()
                    .filter(s -> s.getName().endsWith("Controller"))
                    .limit(5)
                    .collect(Collectors.toList());
            
            for (CodeStructureEntity controller : controllers) {
                String simpleName = controller.getName().replace("Controller", "");
                uml.append("  [").append(simpleName).append("Controller] as ").append(simpleName.toLowerCase()).append("\n");
            }
            uml.append("}\n\n");

            uml.append("' 业务层\n");
            uml.append("package \"业务层\" {\n");
            uml.append("  [业务服务] as service\n");
            uml.append("}\n\n");

            uml.append("' 数据层\n");
            uml.append("package \"数据层\" {\n");
            uml.append("  [数据访问] as repository\n");
            uml.append("  database \"MySQL\" as db\n");
            uml.append("}\n\n");

            uml.append("' 外部系统\n");
            uml.append("package \"外部系统\" {\n");
            uml.append("  [缓存服务\\nRedis] as redis\n");
            uml.append("  [消息队列\\nRabbitMQ] as mq\n");
            uml.append("}\n\n");

            // 添加交互关系
            uml.append("' 交互关系\n");
            uml.append("frontend --> gateway : HTTP请求\n");
            uml.append("gateway --> ").append(controllers.isEmpty() ? "service" : controllers.get(0).getName().replace("Controller", "").toLowerCase()).append(" : 路由转发\n");
            
            for (CodeStructureEntity controller : controllers) {
                String simpleName = controller.getName().replace("Controller", "").toLowerCase();
                uml.append(simpleName).append(" --> service : 调用业务逻辑\n");
            }
            
            uml.append("service --> repository : 数据操作\n");
            uml.append("service --> redis : 缓存读写\n");
            uml.append("service --> mq : 发送消息\n");
            uml.append("repository --> db : SQL查询\n");

            uml.append("\n@enduml");

            return generateDiagram(taskId, "component-interaction", uml.toString());

        } catch (Exception e) {
            log.error("生成组件交互图失败", e);
            return null;
        }
    }

    /**
     * 生成业务流程图
     * 展示主要业务流程
     */
    public String generateBusinessFlowDiagram(String taskId) {
        log.info("生成业务流程图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 找到Service类，从中推断业务流程
            List<CodeStructureEntity> services = structures.stream()
                    .filter(s -> s.getName().endsWith("Service") && !s.getName().contains("Impl"))
                    .limit(3)
                    .collect(Collectors.toList());

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 业务流程图\n");
            uml.append("start\n\n");

            if (!services.isEmpty()) {
                uml.append(":用户发起请求;\n");
                uml.append(":网关验证权限;\n\n");
                
                uml.append("if (权限验证通过?) then (是)\n");
                uml.append("  :Controller接收请求;\n");
                uml.append("  :参数校验;\n\n");
                
                uml.append("  if (参数合法?) then (是)\n");
                uml.append("    :Service处理业务逻辑;\n");
                uml.append("    :查询缓存;\n\n");
                
                uml.append("    if (缓存命中?) then (是)\n");
                uml.append("      :返回缓存数据;\n");
                uml.append("    else (否)\n");
                uml.append("      :查询数据库;\n");
                uml.append("      :更新缓存;\n");
                uml.append("      :返回查询结果;\n");
                uml.append("    endif\n\n");
                
                uml.append("    :组装返回数据;\n");
                uml.append("    :返回成功响应;\n");
                uml.append("  else (否)\n");
                uml.append("    :返回参数错误;\n");
                uml.append("  endif\n");
                
                uml.append("else (否)\n");
                uml.append("  :返回权限不足;\n");
                uml.append("endif\n\n");
            } else {
                uml.append(":系统处理请求;\n");
                uml.append(":返回响应;\n");
            }

            uml.append("stop\n");
            uml.append("@enduml");

            return generateDiagram(taskId, "business-flow", uml.toString());

        } catch (Exception e) {
            log.error("生成业务流程图失败", e);
            return null;
        }
    }

    /**
     * 生成状态机图
     * 展示对象的状态转换
     */
    public String generateStateMachineDiagram(String taskId) {
        log.info("生成状态机图: {}", taskId);

        try {
            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 订单状态机图（示例）\n");
            uml.append("hide empty description\n\n");

            uml.append("[*] --> 待支付 : 创建订单\n");
            uml.append("待支付 --> 已支付 : 支付成功\n");
            uml.append("待支付 --> 已取消 : 取消订单\\n或超时\n");
            uml.append("已支付 --> 处理中 : 开始处理\n");
            uml.append("处理中 --> 已完成 : 处理完成\n");
            uml.append("处理中 --> 处理失败 : 处理异常\n");
            uml.append("处理失败 --> 待退款 : 申请退款\n");
            uml.append("待退款 --> 已退款 : 退款成功\n");
            uml.append("已完成 --> [*]\n");
            uml.append("已取消 --> [*]\n");
            uml.append("已退款 --> [*]\n\n");

            uml.append("' 状态说明\n");
            uml.append("待支付 : 订单已创建\\n等待用户支付\n");
            uml.append("已支付 : 支付完成\\n等待处理\n");
            uml.append("处理中 : 正在处理业务逻辑\n");
            uml.append("已完成 : 订单完成\n");
            uml.append("已取消 : 订单取消\n");
            uml.append("处理失败 : 处理过程出错\n");
            uml.append("待退款 : 等待退款\n");
            uml.append("已退款 : 退款完成\n");

            uml.append("\n@enduml");

            return generateDiagram(taskId, "state-machine", uml.toString());

        } catch (Exception e) {
            log.error("生成状态机图失败", e);
            return null;
        }
    }

    /**
     * 生成设计模式图
     * 展示项目中使用的设计模式
     */
    public String generateDesignPatternDiagram(String taskId) {
        log.info("生成设计模式图: {}", taskId);

        try {
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 设计模式应用图\n");
            uml.append("skinparam classAttributeIconSize 0\n\n");

            // 识别单例模式
            List<String> singletons = structures.stream()
                    .filter(s -> s.getName().contains("Factory") || s.getName().contains("Manager"))
                    .map(CodeStructureEntity::getName)
                    .limit(2)
                    .collect(Collectors.toList());

            if (!singletons.isEmpty()) {
                uml.append("' 单例模式\n");
                uml.append("package \"单例模式\" {\n");
                for (String singleton : singletons) {
                    uml.append("  class ").append(singleton).append(" <<Singleton>> {\n");
                    uml.append("    - instance: ").append(singleton).append("\n");
                    uml.append("    + getInstance(): ").append(singleton).append("\n");
                    uml.append("  }\n");
                }
                uml.append("}\n\n");
            }

            // 识别工厂模式
            List<String> factories = structures.stream()
                    .filter(s -> s.getName().endsWith("Factory"))
                    .map(CodeStructureEntity::getName)
                    .limit(2)
                    .collect(Collectors.toList());

            if (!factories.isEmpty()) {
                uml.append("' 工厂模式\n");
                uml.append("package \"工厂模式\" {\n");
                for (String factory : factories) {
                    uml.append("  class ").append(factory).append(" <<Factory>> {\n");
                    uml.append("    + create(): Object\n");
                    uml.append("  }\n");
                }
                uml.append("}\n\n");
            }

            // 识别策略模式
            List<String> strategies = structures.stream()
                    .filter(s -> s.getName().contains("Strategy") || s.getName().contains("Handler"))
                    .map(CodeStructureEntity::getName)
                    .limit(2)
                    .collect(Collectors.toList());

            if (!strategies.isEmpty()) {
                uml.append("' 策略模式\n");
                uml.append("package \"策略模式\" {\n");
                uml.append("  interface Strategy {\n");
                uml.append("    + execute()\n");
                uml.append("  }\n");
                for (String strategy : strategies) {
                    uml.append("  class ").append(strategy).append(" implements Strategy\n");
                }
                uml.append("}\n\n");
            }

            // 识别观察者模式
            List<String> observers = structures.stream()
                    .filter(s -> s.getName().contains("Listener") || s.getName().contains("Observer"))
                    .map(CodeStructureEntity::getName)
                    .limit(2)
                    .collect(Collectors.toList());

            if (!observers.isEmpty()) {
                uml.append("' 观察者模式\n");
                uml.append("package \"观察者模式\" {\n");
                uml.append("  interface Observer {\n");
                uml.append("    + update()\n");
                uml.append("  }\n");
                for (String observer : observers) {
                    uml.append("  class ").append(observer).append(" implements Observer\n");
                }
                uml.append("}\n\n");
            }

            // 如果没有识别到任何模式，添加通用模式说明
            if (singletons.isEmpty() && factories.isEmpty() && strategies.isEmpty() && observers.isEmpty()) {
                uml.append("' MVC模式\n");
                uml.append("package \"MVC模式\" {\n");
                uml.append("  class Controller <<Controller>>\n");
                uml.append("  class Service <<Service>>\n");
                uml.append("  class Repository <<Repository>>\n");
                uml.append("  class Entity <<Model>>\n");
                uml.append("  \n");
                uml.append("  Controller --> Service\n");
                uml.append("  Service --> Repository\n");
                uml.append("  Repository --> Entity\n");
                uml.append("}\n\n");
            }

            uml.append("@enduml");

            return generateDiagram(taskId, "design-patterns", uml.toString());

        } catch (Exception e) {
            log.error("生成设计模式图失败", e);
            return null;
        }
    }

    /**
     * 生成部署架构图
     * 展示系统的部署架构
     */
    public String generateDeploymentDiagram(String taskId) {
        log.info("生成部署架构图: {}", taskId);

        try {
            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 部署架构图\n");
            uml.append("skinparam nodeStyle rectangle\n\n");

            // 用户端
            uml.append("actor \"用户\" as user\n");
            uml.append("cloud \"互联网\" as internet\n\n");

            // 负载均衡层
            uml.append("node \"负载均衡器\" {\n");
            uml.append("  [Nginx]\n");
            uml.append("}\n\n");

            // 应用服务器集群
            uml.append("node \"应用服务器集群\" {\n");
            uml.append("  node \"服务器1\" {\n");
            uml.append("    [应用实例1]\n");
            uml.append("  }\n");
            uml.append("  node \"服务器2\" {\n");
            uml.append("    [应用实例2]\n");
            uml.append("  }\n");
            uml.append("  node \"服务器N\" {\n");
            uml.append("    [应用实例N]\n");
            uml.append("  }\n");
            uml.append("}\n\n");

            // 缓存层
            uml.append("node \"缓存集群\" {\n");
            uml.append("  database \"Redis\\nMaster\" as redis_master\n");
            uml.append("  database \"Redis\\nSlave\" as redis_slave\n");
            uml.append("}\n\n");

            // 数据库层
            uml.append("node \"数据库集群\" {\n");
            uml.append("  database \"MySQL\\nMaster\" as db_master\n");
            uml.append("  database \"MySQL\\nSlave\" as db_slave\n");
            uml.append("}\n\n");

            // 文件存储
            uml.append("node \"文件存储\" {\n");
            uml.append("  storage \"OSS\\n对象存储\" as oss\n");
            uml.append("}\n\n");

            // 消息队列
            uml.append("node \"消息队列\" {\n");
            uml.append("  queue \"RabbitMQ\" as mq\n");
            uml.append("}\n\n");

            // 监控系统
            uml.append("node \"监控系统\" {\n");
            uml.append("  [Prometheus]\n");
            uml.append("  [Grafana]\n");
            uml.append("}\n\n");

            // 连接关系
            uml.append("' 连接关系\n");
            uml.append("user --> internet\n");
            uml.append("internet --> Nginx\n");
            uml.append("Nginx --> 应用实例1\n");
            uml.append("Nginx --> 应用实例2\n");
            uml.append("Nginx --> 应用实例N\n");
            uml.append("应用实例1 --> redis_master\n");
            uml.append("应用实例1 --> db_master\n");
            uml.append("应用实例1 --> oss\n");
            uml.append("应用实例1 --> mq\n");
            uml.append("redis_master --> redis_slave : 主从复制\n");
            uml.append("db_master --> db_slave : 主从复制\n");
            uml.append("应用实例1 ..> Prometheus : 指标采集\n");
            uml.append("Prometheus ..> Grafana : 数据展示\n");

            uml.append("\n@enduml");

            return generateDiagram(taskId, "deployment-architecture", uml.toString());

        } catch (Exception e) {
            log.error("生成部署架构图失败", e);
            return null;
        }
    }

    /**
     * 生成监控架构图
     * 展示系统的监控体系
     */
    public String generateMonitoringDiagram(String taskId) {
        log.info("生成监控架构图: {}", taskId);

        try {
            StringBuilder uml = new StringBuilder();
            uml.append("@startuml\n");
            uml.append("' 监控架构图\n");
            uml.append("skinparam componentStyle rectangle\n\n");

            // 应用层
            uml.append("package \"应用层\" {\n");
            uml.append("  [应用服务1] as app1\n");
            uml.append("  [应用服务2] as app2\n");
            uml.append("  [应用服务N] as appN\n");
            uml.append("}\n\n");

            // 数据采集层
            uml.append("package \"数据采集层\" {\n");
            uml.append("  [应用日志] as applog\n");
            uml.append("  [系统指标] as sysmetric\n");
            uml.append("  [业务指标] as bizmetric\n");
            uml.append("  [调用链追踪] as trace\n");
            uml.append("}\n\n");

            // 数据处理层
            uml.append("package \"数据处理层\" {\n");
            uml.append("  [日志收集\\nELK] as elk\n");
            uml.append("  [指标收集\\nPrometheus] as prometheus\n");
            uml.append("  [链路追踪\\nSkyWalking] as skywalking\n");
            uml.append("}\n\n");

            // 数据存储层
            uml.append("package \"数据存储层\" {\n");
            uml.append("  database \"时序数据库\\nInfluxDB\" as influxdb\n");
            uml.append("  database \"日志存储\\nElasticsearch\" as es\n");
            uml.append("}\n\n");

            // 展示层
            uml.append("package \"展示层\" {\n");
            uml.append("  [仪表板\\nGrafana] as grafana\n");
            uml.append("  [日志查询\\nKibana] as kibana\n");
            uml.append("}\n\n");

            // 告警层
            uml.append("package \"告警层\" {\n");
            uml.append("  [告警中心\\nAlertManager] as alertmanager\n");
            uml.append("  [通知渠道\\n邮件/短信/钉钉] as notification\n");
            uml.append("}\n\n");

            // 连接关系
            uml.append("' 数据流向\n");
            uml.append("app1 --> applog\n");
            uml.append("app1 --> sysmetric\n");
            uml.append("app1 --> bizmetric\n");
            uml.append("app1 --> trace\n");
            uml.append("applog --> elk\n");
            uml.append("sysmetric --> prometheus\n");
            uml.append("bizmetric --> prometheus\n");
            uml.append("trace --> skywalking\n");
            uml.append("elk --> es\n");
            uml.append("prometheus --> influxdb\n");
            uml.append("es --> kibana\n");
            uml.append("influxdb --> grafana\n");
            uml.append("prometheus --> grafana\n");
            uml.append("prometheus --> alertmanager\n");
            uml.append("alertmanager --> notification\n");

            uml.append("\n@enduml");

            return generateDiagram(taskId, "monitoring-architecture", uml.toString());

        } catch (Exception e) {
            log.error("生成监控架构图失败", e);
            return null;
        }
    }
}

